package org.peterbjornx.formats;

import org.peterbjornx.io.*;
import org.peterbjornx.image.ColorUtil;

import java.awt.*;
import java.awt.image.BufferedImage;
import java.awt.image.ImageObserver;
import java.io.IOException;

/**
 * Created by IntelliJ IDEA.
 * User: PeterbjornX
 * Date: Apr 7, 2009
 * Time: 8:38:25 PM
 * Reads a image in JAGeX format into a standard JAVA image object
 */
public abstract class AbstractJagexImageReader {

	public abstract Image getImage(String name, int id) throws IOException;

    public static Image getImage(int id, RSInputStream stream, RSInputStream stream_1) throws IOException {
        int w,h,w2,h2;
        stream_1.skip(stream.readShort());
        w2 = stream_1.readShort();
        h2 = stream_1.readShort();
        int j = stream_1.readByte();
        int[] palette = new int[j];
        for(int k = 0; k < j - 1; k++)
            palette[k + 1] = stream_1.read3Bytes();

        for(int l = 0; l < id; l++)
        {
            stream_1.skip(2);
            stream.skip(stream_1.readShort() * stream_1.readShort());
            stream_1.skip(1);
        }

        int dx = stream_1.readByte();
        int dy = stream_1.readByte();
        w = stream_1.readShort();
        h = stream_1.readShort();
        int imgType = stream_1.readByte();
        int j1 = w * h;
        int[] imgPixels = new int[j1];
        if(imgType == 0)
        {
            for(int k1 = 0; k1 < j1; k1++)
                imgPixels[k1] = ColorUtil.jagToARGB(stream.read(),palette);

        }
        if(imgType == 1)
        {
            for(int l1 = 0; l1 < w; l1++)
            {
                for(int i2 = 0; i2 < h; i2++)
                    imgPixels[l1 + i2 * w] = ColorUtil.jagToARGB(stream.read(),palette);

            }

        }
        BufferedImage b = new BufferedImage(w,h,BufferedImage.TYPE_INT_ARGB);
        b.setRGB(0,0,w,h,imgPixels,0,w);
        BufferedImage c = new BufferedImage(w+dx,h+dy,BufferedImage.TYPE_INT_ARGB);
        c.getGraphics().drawImage(b,dx,dy,null);
        return c;
    }

    public abstract Image getImageJPG(String s,Component c) throws IOException;
}
